package edu.ynu.se.xiecheng.achitectureclass.common.utils.test;

import org.apache.commons.io.IOUtils;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Base64;
import java.util.Map;

public class ApiCaller {

    // 数据库连接信息
    private static final String DB_URL = "jdbc:mysql://132.232.152.65:3306/20221120114?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "20221120114";
    private static final String DB_PASSWORD = "20221120114";

    // 使用 Token 调用目标接口
    public static String callApiWithToken(String token) {
        // 目标接口 URL
        String apiUrl = "https://open.ys7.com/api/lapp/device/capture";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 手动构建 x-www-form-urlencoded 格式的请求体
        String requestBody = "accessToken=" + token +
                "&deviceSerial=AB9831171" +
                "&channelNo=1" +
                "&quality=4";

        // 创建请求
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.exchange(apiUrl, HttpMethod.POST, requestEntity, Map.class);

        // 解析响应
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.get("data") instanceof Map) {
                Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                return (String) data.get("picUrl"); // 提取 picUrl
            } else {
                throw new RuntimeException("Invalid response format");
            }
        } else {
            throw new RuntimeException("Failed to call API. Status code: " + response.getStatusCode());
        }
    }

    // 将 Picture URL 存入数据库
    public static void savePicUrlToDatabase(String picUrl) {
        String sql = "INSERT INTO camera_snapshot (photo_path, create_time) VALUES (?, NOW())";
        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement stmt = connection.prepareStatement(sql)) {
            // 设置参数
            stmt.setString(1, picUrl); // 图片 URL
            // 执行插入
            stmt.executeUpdate();
            System.out.println("Picture URL saved to database: " + picUrl);
        } catch (Exception e) {
            throw new RuntimeException("Failed to save picture URL to database: " + e.getMessage(), e);
        }
    }

    // 根据 Picture URL 下载图片并转为 Base64 编码
    public static String downloadImageAndConvertToBase64(String picUrl) {
        try {
            // 打开 URL 连接
            URL url = new URL(picUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 获取输入流并读取数据
            try (InputStream inputStream = connection.getInputStream()) {
                byte[] imageBytes = IOUtils.toByteArray(inputStream); // 使用 Apache Commons IO 读取字节数据

                // 转为 Base64 编码
                return Base64.getEncoder().encodeToString(imageBytes);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to download or encode image: " + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        try {
            // 获取 Token
            String token = TokenFetcher.fetchToken(); // 调用 TokenFetcher 类获取 accessToken
            System.out.println("Access Token: " + token);

            // 使用 Token 调用接口
            String picUrl = callApiWithToken(token);
            System.out.println("Picture URL: " + picUrl);

            // 将图片 URL 存入数据库
            savePicUrlToDatabase(picUrl);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
